/**
 * @Title: HomeActivity.java
 * @Package: com.jason.fingerprint.ui
 * @Descripton: TODO
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年10月19日 上午8:19:23
 * @Version: V1.0
 */
package com.jason.fingerprint.ui;

import org.kymjs.aframe.database.KJDB;
import org.kymjs.aframe.ui.BindView;
import org.kymjs.aframe.ui.KJActivityManager;
import org.kymjs.aframe.ui.activity.BaseActivity;
import org.kymjs.aframe.utils.StringUtils;
import org.kymjs.aframe.utils.SystemTool;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.StrictMode;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import android_serialport_api.FingerprintManager;

import com.jason.fingerprint.AppContext;
import com.jason.fingerprint.R;
import com.jason.fingerprint.adapter.HomeModelAdapter;
import com.jason.fingerprint.beans.OrganBean;
import com.jason.fingerprint.beans.UserBean;
import com.jason.fingerprint.beans.ui.ModelBean;
import com.jason.fingerprint.common.DialogHelper;
import com.jason.fingerprint.logic.DatbOrganSyncLogic;
import com.jason.fingerprint.logic.DatbRecordSyncLogic;
import com.jason.fingerprint.logic.DatbSelectOrganByIdSyncLogic;
import com.jason.fingerprint.widget.LoadingDialog;

/**
 * @ClassName: HomeActivity
 * @Description: 主页
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年10月19日 上午8:19:23
 */
@SuppressLint("HandlerLeak")
public class HomeActivity extends BaseActivity {

	private static final String TAG = "HomeActivity";

	@BindView(id = R.id.home_gridview)
	private GridView mGridView;
	private TextView mUsernfoTextView;

	private HomeModelAdapter mHomeModelAdapter;
	private KJDB mKjdb;
	private LoadingDialog mProgressDialog;
	private boolean isAyncData = false;// 是否正在同步数据

	@BindView(id = R.id.header_title)
	private TextView mTitleTextView;
	
	private long mExitTime = 0;

	@Override
	public void setRootView() {
		setContentView(R.layout.activity_home);
	}

	// 初始化视图
	@Override
	protected void initWidget() {
		super.initWidget();
		if (android.os.Build.VERSION.SDK_INT > 9) {
		    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		    StrictMode.setThreadPolicy(policy);
		}
		mTitleTextView.setText("社区矫正");
		mKjdb = AppContext.getInstance().getKjdb();
		// mGridView = (GridView) findViewById(R.id.home_gridview);
		mHomeModelAdapter = new HomeModelAdapter(this);
		mGridView.setAdapter(mHomeModelAdapter);
		mGridView.setOnItemClickListener(new HomeModelItemClickListener());
		mGridView.setSelector(new ColorDrawable(Color.TRANSPARENT));

		mUsernfoTextView = (TextView) findViewById(R.id.home_info);
		mProgressDialog = new LoadingDialog(this);
		mProgressDialog.setMessage("数据正在加载中，请稍等...");
	}

	// 初始化数据
	@Override
	protected void initData() {
		super.initData();
		// 加载登录帐号下可选择的隶属机构
		if (SystemTool.checkNet(AppContext.getAppContext())) {
			// 初始化人员部门信息
			mKjdb.deleteByWhere(OrganBean.class, null);
			DatbOrganSyncLogic datbOrganSyncLogic = new DatbOrganSyncLogic(
					AppContext.getInstance(), mRecordSyncHandler, false);
			datbOrganSyncLogic.execute();
			// 初始化矫正人员信息
			if (!mProgressDialog.isShowing()) {
				mProgressDialog.show();
			}
			initRecordSync(1);
		}
		updateUserInfo();
	}

	// 更新用户信息
	private void updateUserInfo() {
		mUsernfoTextView.setVisibility(View.VISIBLE);
		UserBean bean = AppContext.getInstance().getUserBean();
		StringBuffer buffer = new StringBuffer();
		if (AppContext.getInstance().isLogin()) {
			Log.i(TAG, bean.toString());
			String name = bean.getUserName();
			if (!StringUtils.isEmpty(name)) {
				buffer.append("登录用户：");
				buffer.append(name);
			}
			buffer.append("    隶属机构：" + bean.getOrgan());
			mUsernfoTextView.setText(buffer.toString());
		} else {
			mUsernfoTextView.setVisibility(View.GONE);
		}
	}

	// 档案同步
	private Handler mRecordSyncHandler = new Handler() {

		@Override
		public void handleMessage(android.os.Message msg) {
			if (mProgressDialog != null) {
				mProgressDialog.cancel();
			}
			isAyncData = false;
			int code = msg.arg1;
			switch (code) {
			case 0:
				Toast.makeText(AppContext.getAppContext(),
						"同步成功,共计" + msg.arg2 + "名，查看具体信息请到档案查询中查询",
						Toast.LENGTH_LONG).show();
				break;

			default:
				Toast.makeText(AppContext.getAppContext(), "同步失败", Toast.LENGTH_SHORT).show();
				break;
			}
		}
	};

	// 进入指纹录入鉴权
	private Handler mAuthorityRecordHandle = new Handler() {

		@Override
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 0:
				Intent intent = new Intent(HomeActivity.this,
						RecordActivity.class);
				intent.putExtra(RecordActivity.RECORD_STATE,
						RecordActivity.ADD_RECORD_STATE);
				startActivity(intent);
				break;
			case 1:
				String error = (String) msg.obj;
				Toast.makeText(AppContext.getAppContext(), error, Toast.LENGTH_SHORT).show();
			default:
				Toast.makeText(AppContext.getAppContext(), "权限不足，无法访问", Toast.LENGTH_SHORT)
						.show();
				break;
			}
		};
	};

	private class HomeModelItemClickListener implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			ModelBean bean = (ModelBean) parent.getItemAtPosition(position);
			switch (bean.getIconId()) {
			case R.drawable.module_icon_luru_selector:
				// TODO 指纹录入
				if (isAyncData) {
					Toast.makeText(AppContext.getAppContext(), "数据正在同步中,请稍等...",
							Toast.LENGTH_SHORT).show();
					return;
				}
				if (SystemTool.checkNet(AppContext.getAppContext())) {
					// 鉴权，只有权限的人才能指纹录入或者修改，此接口现在有问题？？？？？？
					DatbSelectOrganByIdSyncLogic logic = new DatbSelectOrganByIdSyncLogic(
							AppContext.getInstance(), mAuthorityRecordHandle, true);
					logic.execute();
				} else {
					DialogHelper.openNetSettingsDialog(HomeActivity.this);
				}
				break;
			case R.drawable.module_icon_tongbu_selector:
				// 档案同步
				if (isAyncData) {
					Toast.makeText(AppContext.getAppContext(), "数据正在同步中,请稍等...",
							Toast.LENGTH_SHORT).show();
					return;
				}
				initRecordSync(2);
				break;
			case R.drawable.module_icon_chaxun_selector:
				// TODO 档案查询
				if (isAyncData) {
					Toast.makeText(AppContext.getAppContext(), "数据正在同步中,请稍等...",
							Toast.LENGTH_SHORT).show();
					return;
				}
				Intent intent = new Intent(HomeActivity.this,
						RecordActivity.class);
				intent.putExtra(RecordActivity.RECORD_STATE,
						RecordActivity.QUERY_RECORD_STATE);
				startActivity(intent);
				break;
			case R.drawable.module_icon_fuwu_selector:
				// TODO 社区服务
				if (isAyncData) {
					Toast.makeText(AppContext.getAppContext(), "数据正在同步中,请稍等...",
							Toast.LENGTH_SHORT).show();
					return;
				}
				Intent communityServiceIntent = new Intent(HomeActivity.this,
						CommunityServiceActivity.class);
				communityServiceIntent.putExtra("CommunityService", true);
				startActivity(communityServiceIntent);
				break;
			case R.drawable.module_icon_xuexi_selector:
				// TODO 教育学习
				if (isAyncData) {
					Toast.makeText(AppContext.getAppContext(), "数据正在同步中,请稍等...",
							Toast.LENGTH_SHORT).show();
					return;
				}
				Intent studyServiceIntent = new Intent(HomeActivity.this,
						CommunityServiceActivity.class);
				studyServiceIntent.putExtra("CommunityService", false);
				startActivity(studyServiceIntent);
				break;
			case R.drawable.module_icon_baodao_selector:
				// TODO 日常报到
				if (isAyncData) {
					Toast.makeText(AppContext.getAppContext(), "数据正在同步中,请稍等...",
							Toast.LENGTH_SHORT).show();
					return;
				}
				startActivity(new Intent(HomeActivity.this,
						DailyReportActivity.class));
				break;
			case R.drawable.module_icon_zoufang_selector:
				// TODO 工作走访
				if (isAyncData) {
					Toast.makeText(AppContext.getAppContext(), "数据正在同步中,请稍等...",
							Toast.LENGTH_SHORT).show();
					return;
				}
				startActivity(new Intent(HomeActivity.this,
						WorkVisitActivity.class));
				break;
			case R.drawable.module_icon_qingjia_selector:
				// TODO 外出请假
				if (isAyncData) {
					Toast.makeText(AppContext.getAppContext(), "数据正在同步中,请稍等...",
							Toast.LENGTH_SHORT).show();
					return;
				}
				startActivity(new Intent(HomeActivity.this,
						LeaveOutActivity.class));
				break;
			case R.drawable.module_icon_tongzhi_selector:
				// TODO 工作通知
				// workNotice();
				startActivity(new Intent(HomeActivity.this,
						WorkNotifyActivity.class));
				break;
			case R.drawable.module_icon_tixing_selector:
				// TODO 工作提醒
				startActivity(new Intent(HomeActivity.this,
						WorkRemindActivity.class));
				break;
			case R.drawable.module_icon_peizhi_selector:
				// TODO 系统配置
				startActivity(new Intent(HomeActivity.this,
						SettingActivity.class));
				break;
			case R.drawable.module_icon_women_selector:
				// TODO 关于我们
				startActivity(new Intent(HomeActivity.this, AboutActivity.class));
				break;

			default:
				break;
			}
		}

	}

	// 档案同步
	private void initRecordSync(int state) {
		if (SystemTool.checkNet(AppContext.getAppContext())) {
			if (!isAyncData) {
				if (state == 2) {//点击加载的收
					mProgressDialog.setTitle("数据同步");
					mProgressDialog.setMessage("正在同步档案中，请稍等...");
					mProgressDialog.show();
				}
				// 同步数据之前，需要把old data delete
				isAyncData = true;
				DatbRecordSyncLogic datbRecordSyncLogic = new DatbRecordSyncLogic(
						AppContext.getInstance(), mRecordSyncHandler, true);
				datbRecordSyncLogic.execute();
			} else {
				Toast.makeText(AppContext.getAppContext(), "数据正在同步中",
						Toast.LENGTH_SHORT).show();
			}
		} else {
			if (state == 2) {
				DialogHelper.openNetSettingsDialog(HomeActivity.this);
			}
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_DOWN) {
			if ((System.currentTimeMillis() - mExitTime) > 2000) {
				Toast.makeText(AppContext.getAppContext(), "再按一次退出应用",
						Toast.LENGTH_SHORT).show();
				mExitTime = System.currentTimeMillis();
			} else {
				KJActivityManager.create().AppExit(HomeActivity.this);
				FingerprintManager.getInstance().closeSerialPort();
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

}
